import pygame
from typing import Callable

from . import util


class Button:
    def __init__(self, x, y, width, height, text, t_size=18, t_color=(255, 255, 255),
                 bg_color=(63, 67, 78),
                 bg_hover_color=(36, 38, 47),
                 bg_click_color=(63, 67, 78)):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.t_size = t_size
        self.t_color = t_color
        self.bg_color = bg_color
        self.bg_hover_color = bg_hover_color
        self.bg_click_color = bg_click_color
        self.font = pygame.font.Font(
            util.get_resource_path('gobang/font/STLITI.TTF'), t_size)

    def draw(self, surface):
        color = self.bg_hover_color if self.is_hovered() else self.bg_color
        color = self.bg_click_color if self.is_clicked() else color
        pygame.draw.rect(surface, color, self.rect)

        text_surface = self.font.render(self.text, True, self.t_color)
        text_rect = text_surface.get_rect(center=self.rect.center)
        surface.blit(text_surface, text_rect)

    def is_hovered(self) -> bool:
        mouse_pos = pygame.mouse.get_pos()
        return self.rect.collidepoint(mouse_pos)

    def is_clicked(self) -> bool:
        """这个只要单击就会触发，所以为连续触发"""
        mouse_pressed = pygame.mouse.get_pressed()
        return mouse_pressed[0] and self.is_hovered()

    def handle_event(self, event: pygame.event.Event, func: Callable):
        if event.type == pygame.MOUSEBUTTONUP:
            if self.is_hovered():
                func()
